/*
 *所有关于ReplenishmentList类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*ReplenishmentListService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using Mercury.Core.BaseProvider;
using Mercury.Core.Extensions.AutofacManager;
using Mercury.Entity.DomainModels;
using System.Linq;
using Mercury.Core.Utilities;
using System.Linq.Expressions;
using Mercury.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using Mercury.Order.IRepositories;
using System.Threading.Tasks;
using Mercury.Core.Common;
using System.Collections.Generic;
using System;

namespace Mercury.Order.Services
{
    public partial class ReplenishmentListService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IReplenishmentListRepository _repository;//访问数据库

        [ActivatorUtilitiesConstructor]
        public ReplenishmentListService(
            IReplenishmentListRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }

        public async Task<WebResponseContent> GetReplenishmentListInfo(string orderNo)
        {
            var order = await repository.FindFirstAsync(c => c.Id == orderNo && c.DeletionFlag != 1);
            if (order == null)
                return Response.Error("订单不存在,或已经被处理！");

            var details = repository.DbContext.Set<ReplenishmentListDetails>().Where(c => c.ReplenishmentListId == order.Id).ToList();
            var orderElements = repository.DbContext.Set<ReplenishmentLisElement>().Where(c => c.ReplenishmentLisId == order.Id).ToList();

            var orderForm = repository.DbContext.Set<OrderForm>().FirstOrDefault(c => c.OrderNumber == order.OrderNumber);
            var queryable = repository.DbContext.Set<ProductData>().Where(c => c.Name == orderForm.SteelGrade && c.DeletionFlag != 1);
            var productElements = repository.DbContext.Set<ProductElementBOM>().Join(queryable, s => s.ProductId, t => t.Id, (s, t) => s).ToList();

            var elements = repository.DbContext.Set<BaseElement>().Where(c => c.DeletionFlag != 1).ToList();

            var data = new List<Dictionary<string, Object>>();

            var row1 = new Dictionary<string, Object>
            {
                { "Column1", "炉中钢水重量" },
                { "Column2", "目标成分" },
                { "Column3", "" },
                { "CellStyle", new {
                    Column2 = new Dictionary<string,string>
                    {
                        { "color","red"}      ,
                        { "font-weight","900"}
                    }
                } }
            };

            var total = order.SteelWeight + order.PlannedReplenishmentQuantity;
            var row2 = new Dictionary<string, Object>
            {
                { "Column1", order.SteelWeight },
                { "Column2", "分析成分" },
                { "Column3", "" },
                { "CellStyle", new {
                    Column2 = new Dictionary<string,string>
                    {
                        { "color","red"}      ,
                        { "font-weight","900"}
                    }
                } }
            };

            var varField = new Dictionary<string, double>();
            foreach (var item in productElements)
            {
                var element = elements.First(c => c.Id == item.ElementId);
                varField.Add(element.ElementSymbols.ToLower(), 0);
                row1[element.ElementSymbols.ToLower()] = item.TargetProportion;
            }

            data.Add(row1);
            data.Add(row2);



            int index = 0;
            var list = details.Where(c => c.IngredientsType < 2).OrderBy(c => c.MaterialId).ToList();
            foreach (var item in list)
            {
                index++;
                var materialElementRateTarget = new Dictionary<string, Object>()
                {
                    { "Column1",order.SteelWeight}    ,
                    { "Column2", item.BatchNumber + (string.IsNullOrEmpty(item.MaterialBoxNo)?"":$" ({item.MaterialBoxNo})") },
                    { "Column3", "加入量" }
                };
                var materialElementRate = new Dictionary<string, Object>()
                {
                    { "Column1",index == list.Count? "配入后钢水重量": order.SteelWeight}    ,
                    { "Column2", item.MaterialName },
                    { "Column3",item.RequiredWeight }
                };
                foreach (var ele in orderElements.Where(c => c.ReplenishmentLisDetailsId == item.Id))
                {
                    var rate = (item.RequiredWeight.ToDecimal() * ele.ElementContent / total).GetDouble();
                    var element = elements.First(c => c.Id == ele.ElementId);
                    varField[element.ElementSymbols.ToLower()] += rate;
                    materialElementRateTarget.Add(element.ElementSymbols.ToLower(), ele.ElementContent);
                    materialElementRate.Add(element.ElementSymbols.ToLower(), (item.RequiredWeight.ToDecimal() * ele.ElementContent / order.SteelWeight).GetDouble().ToString("F6"));
                }
                data.Add(materialElementRateTarget);
                data.Add(materialElementRate);
            }

            var sumRow = new Dictionary<string, object>
            {
                { "Column1", total.ToDouble() },
                { "Column2", "实际配入成分" }
            };
            foreach (var item in varField)
            {
                sumRow.Add(item.Key, item.Value.ToString("F6"));
            }
            data.Add(sumRow);

            return Response.OK("", new
            {
                varField = varField.Keys.ToList(),
                data  ,
                orderForm.SteelGrade
            });
        }
    }
}
